package com.campol.utils;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.campol.extlogger.ExtLogger;
import com.campol.model.PostModel;
import com.campol.model.Reporter;

public class CustomXmlParser {

	public static boolean parseXmlForAddedPoint(String xml) {
		if (xml != null) {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			try {
				DocumentBuilder domBuilder = dbf.newDocumentBuilder();
				InputSource is = new InputSource();
	            is.setCharacterStream(new StringReader(xml));
	            Document doc = domBuilder.parse(is);
	            
	            NodeList nodes = doc.getElementsByTagName("message");
	            if (nodes != null && nodes.getLength() > 0) {
	            	Node node = nodes.item(0);
	            	String value = node.getFirstChild().getNodeValue();
	            	if ("Point added".equalsIgnoreCase(value)) {
	            		return true;
	            	}
	            }
			} catch (Exception e) {
				ExtLogger.getInstance().writeLog(new Date(), "CustomXmlParser.parseXmlForAddedPoint()", "Exception. "+e.toString());
				return false;
			}
		}
		return false;
	}

	/*<response type="users">
	<items>
		<item>
			<user_id>2</user_id>
			<fname>Test</fname>
			<lname>Tester</lname>
			<image>http://fartkontrollerne.dk/api/get_user_image.php?tocken=d54d88abc64cc809d51b117431b6cd42&amp;user_id=2</image>
		</item>
		<item>
		...
		</item>
	</items>
	</response>*/
	public static ArrayList<Reporter> parseXmlForTopReporters(String xml) {
		ArrayList<Reporter> list = null;
		if (xml != null) {
			list = new ArrayList<Reporter>();
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			try {
				DocumentBuilder domBuilder = dbf.newDocumentBuilder();
				InputSource is = new InputSource();
				is.setCharacterStream(new StringReader(xml));
				Document doc = domBuilder.parse(is);
				
				NodeList nodes = doc.getElementsByTagName("item");
				for (int i = 0; i < nodes.getLength(); i++) {
					Node item = nodes.item(i);
					String nodeName = item.getNodeName();
					if ("item".equals(nodeName)) {
						Reporter reporter = new Reporter();
						NodeList itemChilds = item.getChildNodes();
						for (int j = 0; j < itemChilds.getLength(); j++) {
							Node child = itemChilds.item(j);
							nodeName = child.getNodeName();
							if ("user_id".equals(nodeName)) {
								reporter.Id = Long.parseLong(child.getFirstChild().getNodeValue());
							} else if ("fname".equals(nodeName)) {
								reporter.FirstName = child.getFirstChild().getNodeValue();
							} else if ("lname".equals(nodeName)) {
								reporter.LastName = child.getFirstChild().getNodeValue();
							} else if ("image".equals(nodeName)) {
								reporter.ImageUrl = child.getFirstChild().getNodeValue();
							}
						}
						list.add(reporter);
	            	}
				}
			} catch (Exception e) {
				ExtLogger.getInstance().writeLog(new Date(), "CustomXmlParser.parseXmlForTopReporters()", "Exception. "+e.toString());
				return null;
			}
		}
		return list;
	}
	
	/*<items><item><lat>53.853794</lat>
			       <long>27.599295</long>
				   <distance_to>0.179751907550814</distance_to>
				   <country_code>BY</country_code>
	               <place>ул. Гуляма Якубова, Серебрянка-2, 3, 4, Серебрянка, Ленинский район г. Минска, Minsk, Минская область, 722095, Belarus</place>
				   <country>Belarus</country>
				   <state>Минская область</state>
	 			   <post_code>722095</post_code>
				   <state_district></state_district>
				   <county></county>
				   <city>Minsk</city>
				   <suburb>Серебрянка</suburb>
				   <road>ул. Гуляма Якубова</road>
				   <house_number></house_number>
				   <int_type>1</int_type>
				   <type>Camera</type></item>*/
	public static ArrayList<PostModel> parseXmlForPostList(String xml) {
		ArrayList<PostModel> list = null;
		if (xml != null) {
			list = new ArrayList<PostModel>();

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			try {
				DocumentBuilder domBuilder = dbf.newDocumentBuilder();
				InputSource is = new InputSource();
	            is.setCharacterStream(new StringReader(xml));
	            Document doc = domBuilder.parse(is);
	            
	            NodeList nodes = doc.getElementsByTagName("item");
	            
	            for (int i = 0; i < nodes.getLength(); i++) {
	            	Node item = nodes.item(i);
	            	
	            	String nodeName = item.getNodeName();
	            	if ("item".equals(nodeName)) {
	            		PostModel postModel = new PostModel();
	            		NodeList itemChilds = item.getChildNodes();
	            		for (int j = 0; j < itemChilds.getLength(); j++) {
	            			Node child = itemChilds.item(j);
	            			nodeName = child.getNodeName();
	            			if ("lat".equals(nodeName)) {
	            				String value = child.getFirstChild().getNodeValue();
	            				double lat = Double.parseDouble(value);
	            				postModel.Latitude = lat;
	            			} else if ("long".equals(nodeName)) {
	            				String value = child.getFirstChild().getNodeValue();
	            				double lng = Double.parseDouble(value);
	            				postModel.Longitude = lng;
	            			} else if ("type".equals(nodeName)) {
	            				String value = child.getFirstChild().getNodeValue();
	            				if ("Camera".equalsIgnoreCase(value)) {
	            					postModel.IsCamera = true;
	            				} 
	            			} else if ("road".equalsIgnoreCase(nodeName)) {
	            				if (child.getFirstChild() != null)
	            					postModel.Road = child.getFirstChild().getNodeValue();
	            			} else if ("place".equalsIgnoreCase(nodeName)) {
	            				if (child.getFirstChild() != null)
	            					postModel.Place = child.getFirstChild().getNodeValue();
	            			} else if ("distance".equalsIgnoreCase(nodeName)) {
	            				String value = child.getFirstChild().getNodeValue();
	            				double dist = Double.parseDouble(value);
	            				int roundedDist = (int) Math.round(dist);
	            				postModel.Distance = String.format("%d km", roundedDist);
	            			}
	            		}
	            		list.add(postModel);
	            	}
	            }

			} catch (Exception e) {
				ExtLogger.getInstance().writeLog(new Date(), "CustomXmlParser.parseXmlForPostList()", "Exception. "+e.toString());
				return null;
			}
			
			return list;
		}
		return list;
	}
	
	public static boolean parseXmlForRegistratedUser(String xml) {
		if (xml != null) {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			try {
				DocumentBuilder domBuilder = dbf.newDocumentBuilder();
				InputSource is = new InputSource();
	            is.setCharacterStream(new StringReader(xml));
	            Document doc = domBuilder.parse(is);
	            
	            NodeList nodes = doc.getElementsByTagName("response");
	            if (nodes != null && nodes.getLength() > 0) {
	            	for (int i = 0; i < nodes.getLength(); i++) {
	            		Node node = nodes.item(0);
	            		String value = node.getNodeName();
	            		if ("response".equals(value)) {
	            			NamedNodeMap map = node.getAttributes();
	            			Node type = map.getNamedItem("type");
	            			String val = type.getNodeValue();
	            			if ("registration_success".equalsIgnoreCase(val)) {
	            				return true;
	            			}
	            		}
	            	}
	            }
			} catch (Exception e) {
				ExtLogger.getInstance().writeLog(new Date(), "CustomXmlParser.parseXmlForRegistratedUser()", "Exception. "+e.toString());
				return false;
			}
		}
		return false;
	}
	
	// <?xml version="1.0" encoding="UTF-8"?><response type="error"><message>Wrong tocken key</message></response>
	public static boolean parseXmlForTokenIsValid(String xml) {
		if (xml != null) {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			try {
				DocumentBuilder domBuilder = dbf.newDocumentBuilder();
				InputSource is = new InputSource();
	            is.setCharacterStream(new StringReader(xml));
	            Document doc = domBuilder.parse(is);
	            
	            NodeList nodes = doc.getElementsByTagName("response");
	            if (nodes != null && nodes.getLength() > 0) {
	            	for (int i = 0; i < nodes.getLength(); i++) {
	            		Node node = nodes.item(0);
	            		String value = node.getNodeName();
	            		if ("response".equals(value)) {
	            			NamedNodeMap map = node.getAttributes();
	            			Node type = map.getNamedItem("type");
	            			String val = type.getNodeValue();
	            			if (!"error".equalsIgnoreCase(val)) {
	            				return true;
	            			}
	            		}
	            	}
	            }
			} catch (Exception e) {
				ExtLogger.getInstance().writeLog(new Date(), "CustomXmlParser.parseXmlForTokenIsValid()", "Exception. "+e.toString());
				return false;
			}
		}
		return false;
	}
	
	//<response type="login_success"><message>Successfully logged</message><tocken>3210ef3d5ebb52cc887c5d6dada50ce6</tocken></response>
	public static String parseXmlForToken(String xml) {
		if (xml != null) {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			try {
				DocumentBuilder domBuilder = dbf.newDocumentBuilder();
				InputSource is = new InputSource();
	            is.setCharacterStream(new StringReader(xml));
	            Document doc = domBuilder.parse(is);
	            
	            NodeList nodes = doc.getElementsByTagName("response");
	            if (nodes != null && nodes.getLength() > 0) {
	            	for (int i = 0; i < nodes.getLength(); i++) {
	            		Node node = nodes.item(i);
	            		String value = node.getNodeName();
	            		if ("response".equals(value)) {
	            			NamedNodeMap map = node.getAttributes();
	            			Node type = map.getNamedItem("type");
	            			String val = type.getNodeValue();
	            			if (!"login_success".equalsIgnoreCase(val)) {
	            				return null;
	            			}
	            			NodeList list = doc.getElementsByTagName("tocken");
	            			if (list != null && list.getLength()>0) {
	            				for (int j = 0; j < list.getLength();j++) {
	            					Node nd = list.item(j);
	            					String v = nd.getNodeName();
	            					if ("tocken".equals(v)) {
	            						return nd.getFirstChild().getNodeValue();
	            					}
	            				}
	            			}
	            		}
	            	}
	            } 
			} catch (Exception e) {
				ExtLogger.getInstance().writeLog(new Date(), "CustomXmlParser.parseXmlForToken()", "Exception. "+e.toString());
				return null;
			}
		}
		return null;
	}
}
